import { _decorator, Component } from 'cc';
import { GlobalEventBus } from '../core/EventBus';

const { ccclass, property } = _decorator;

export type WeaponSlot = 'primary' | 'secondary';

export interface WeaponState {
  id: string;
  mag: number;
  reserve: number;
  rof: number; // rounds per second
  reload: number; // seconds
  magazineSize: number;
}

@ccclass('WeaponController')
export class WeaponController extends Component {
  @property
  public activeSlot: WeaponSlot = 'primary';

  private primary: WeaponState = { id: 'P9', mag: 12, reserve: 36, rof: 8.5, reload: 1.6, magazineSize: 12 };
  private secondary: WeaponState = { id: 'SMG-11', mag: 32, reserve: 0, rof: 12, reload: 1.8, magazineSize: 32 };

  getActive(): WeaponState {
    return this.activeSlot === 'primary' ? this.primary : this.secondary;
  }

  /** 返回当前完整状态（用于HUD和系统同步） */
  public getCurrent(): {
    id: string;
    mag: number;
    reserve: number;
    magazineSize: number;
    rof: number;
    reloadSec: number;
    slot: WeaponSlot;
  } {
    const s = this.getActive();
    return {
      id: s.id,
      mag: s.mag,
      reserve: s.reserve,
      magazineSize: s.magazineSize,
      rof: s.rof,
      reloadSec: s.reload,
      slot: this.activeSlot,
    };
  }

  getActiveWeaponId(): string { return this.getActive().id; }
  getActiveMag(): number { return this.getActive().mag; }
  getActiveReserve(): number { return this.getActive().reserve; }
  getActiveROF(): number { return this.getActive().rof; }
  getActiveReload(): number { return this.getActive().reload; }
  getActiveMagazineSize(): number { return this.getActive().magazineSize; }

  public setLoadout(primary: WeaponState, secondary: WeaponState, active: WeaponSlot = 'primary') {
    this.primary = { ...primary };
    this.secondary = { ...secondary };
    this.activeSlot = active;
    if (typeof console !== 'undefined' && console.debug) {
      console.debug(
        `[WC] setLoadout ${this.primary.id} mag=${this.primary.mag} reserve=${this.primary.reserve} | ${this.secondary.id} mag=${this.secondary.mag} reserve=${this.secondary.reserve}`
      );
    }
    this.emitAmmoChanged();
  }

  public getActiveSlot(): WeaponSlot {
    return this.activeSlot;
  }

  /**
   * 扣除一发弹药。成功返回 true；若弹匣为空返回 false。
   * 会触发 ammo/changed；若变为 0 再触发 ammo/out。
   */
  public consumeOneRound(): boolean {
    const s = this.getActive();
    if (s.mag <= 0) {
      return false;
    }
    s.mag -= 1;
    if (typeof console !== 'undefined' && console.debug) {
      console.debug('[AMMO] mag:', s.mag, 'reserve:', s.reserve);
    }
    this.emitAmmoChanged();
    if (s.mag === 0) {
      if (typeof console !== 'undefined' && console.debug) {
        console.debug('[AMMO] out');
      }
      GlobalEventBus.emit('ammo/out', { weaponId: s.id });
    }
    return true;
  }

  public canReload(): boolean {
    const s = this.getActive();
    return s.reserve > 0 && s.mag === 0;
  }

  public reloadOnce(): void {
    const s = this.getActive();
    if (!(s.reserve > 0 && s.mag === 0)) return;
    GlobalEventBus.emit('reload/begin', { weaponId: s.id, t: s.reload });
    const needed = s.magazineSize - s.mag;
    const loaded = Math.min(needed, s.reserve);
    s.mag += loaded;
    s.reserve -= loaded;
    GlobalEventBus.emit('reload/end', { weaponId: s.id });
    this.emitAmmoChanged();
  }

  public trySwitchSecondary(): boolean {
    const nextSlot: WeaponSlot = this.activeSlot === 'primary' ? 'secondary' : 'primary';
    const next = nextSlot === 'primary' ? this.primary : this.secondary;
    if (next.mag > 0 || next.reserve > 0) {
      this.activeSlot = nextSlot;
      GlobalEventBus.emit('weapon/switch', { slot: this.activeSlot, weaponId: next.id });
      this.emitAmmoChanged();
      return true;
    }
    return false;
  }

  /** 立刻广播当前弹药状态，便于HUD在开场同步 */
  public broadcast(): void {
    this.emitAmmoChanged();
  }

  private emitAmmoChanged() {
    const s = this.getActive();
    GlobalEventBus.emit('ammo/changed', { weaponId: s.id, mag: s.mag, reserve: s.reserve });
  }
}

export default WeaponController;
